package com.kungfuhacking.wristbandpro.my.presenter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.location.bean.OldEntity;
import com.kungfuhacking.wristbandpro.my.FragmentMy;
import com.kungfuhacking.wristbandpro.my.activity.AboutUsActivity;
import com.kungfuhacking.wristbandpro.my.activity.AddOldActivity;
import com.kungfuhacking.wristbandpro.my.activity.SettingActivity;
import com.kungfuhacking.wristbandpro.utils.Constant;

import java.util.List;
import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.content.ContentValues.TAG;
import static com.kungfuhacking.wristbandpro.R.id.rl_info;
import static com.kungfuhacking.wristbandpro.R.id.tv_notice;


/**
 * Created by Aaron on 17/5/15.
 */

public class FamilyAdapter extends RecyclerView.Adapter<FamilyAdapter.MyViewHolder> implements View.OnClickListener {

    private Context context;
    private List<OldEntity> oldEntities;

    private static final int HEAD = -1;
    private static final int NORMAL = 0;
    private static final int BOTTOM = 1;
    private final SharedPreferences sp;
    private boolean isNotice;//是否 推送通知
    private FragmentMy fragmentMy;
    private int index;
    int[] bgArray = {R.mipmap.ic_my_bg1, R.mipmap.ic_my_bg2, R.mipmap.ic_my_bg3,
            R.mipmap.ic_my_bg4, R.mipmap.ic_my_bg5, R.mipmap.ic_my_bg6};

    public FamilyAdapter(Context context, List<OldEntity> oldEntities, FragmentMy fragmentMy) {
        sp = context.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);
        getBackground();
        this.context = context;
        this.oldEntities = oldEntities;
        this.fragmentMy = fragmentMy;
    }

    /**
     * 获取背景图
     */
    private void getBackground() {
        Random random = new Random();
        index = random.nextInt(6);
    }

    @Override
    public FamilyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {

            case HEAD:
                return new FamilyAdapter.MyViewHolder(
                        LayoutInflater.from(context).inflate(R.layout.item_head_my, parent,
                                false), viewType);
            case NORMAL:
                return new FamilyAdapter.MyViewHolder(
                        LayoutInflater.from(context).inflate(R.layout.item_old_family, parent,
                                false), viewType);
            case BOTTOM:
                return new FamilyAdapter.MyViewHolder(
                        LayoutInflater.from(context).inflate(R.layout.item_bottom_my, parent,
                                false), viewType);
        }

        return null;

    }

    @Override
    public void onBindViewHolder(FamilyAdapter.MyViewHolder holder, int position) {

        switch (getItemViewType(position)) {
            case HEAD:
                holder.sdvHeadViewMy.setImageURI(Uri.parse(sp.getString(Constant.USER_IMG, "")));
                holder.tvNameMy.setText(sp.getString(Constant.NICKNAME, ""));
                holder.sdvHeadViewMy.setOnClickListener(this);
                holder.rlInfo.setBackgroundResource(bgArray[index]);
                break;
            case NORMAL:
                --position;
                holder.tvName.setText(oldEntities.get(position).getNickName());
                holder.sdvHeadView.setImageURI(Uri.parse(
                        TextUtils.isEmpty(oldEntities.get(position).getPicUrl()) ? ""
                                : oldEntities.get(position).getPicUrl()));
                break;
            case BOTTOM:

                holder.tvNotice.setOnClickListener(this);
                holder.mivAboutUs.setOnClickListener(this);
                holder.mivClearCache.setOnClickListener(this);
                holder.rlAddOld.setOnClickListener(this);
//                holder.tvVersionInfo.setOnClickListener(this);
                holder.tvExit.setOnClickListener(this);
                holder.tvVersionInfo.setText(getCurrentVersion());

                isNotice = sp.getBoolean(Constant.IS_NOTICE, true);
                holder.tvNotice.setSelected(isNotice);

                break;

        }

    }

    @Override
    public int getItemViewType(int position) {

        if (oldEntities == null)
            return super.getItemViewType(position);

        if (position == 0)
            return HEAD;
        else if (position == oldEntities.size() + 1)
            return BOTTOM;
        else
            return NORMAL;

    }

    @Override
    public int getItemCount() {
        return oldEntities.size() + 2;
    }

    public void setOldEntities(List<OldEntity> oldEntities) {
        this.oldEntities = oldEntities;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        SimpleDraweeView sdvHeadViewMy;
        SimpleDraweeView sdvHeadView;
        TextView tvName;
        TextView tvNameMy;
        TextView tvVersionInfo;
        TextView tvExit;
        ImageView tvNotice;
        RelativeLayout mivAboutUs;
        RelativeLayout mivClearCache;
        RelativeLayout rlInfo;
        RelativeLayout rlAddOld;

        MyViewHolder(View view, int viewType) {
            super(view);

            switch (viewType) {

                case HEAD:
                    sdvHeadViewMy = (SimpleDraweeView) view.findViewById(R.id.sdv_head);
                    tvNameMy = (TextView) view.findViewById(R.id.tv_name);
                    rlInfo = (RelativeLayout) view.findViewById(rl_info);
                    break;
                case NORMAL:
                    this.sdvHeadView = (SimpleDraweeView) view.findViewById(R.id.sdvHeadView);
                    tvName = (TextView) view.findViewById(R.id.tvName);
                    break;
                case BOTTOM:
                    tvNotice = (ImageView) view.findViewById(tv_notice);
                    mivAboutUs = (RelativeLayout) view.findViewById(R.id.miv_about_us);
                    mivClearCache = (RelativeLayout) view.findViewById(R.id.miv_clear_cache);
                    rlAddOld = (RelativeLayout) view.findViewById(R.id.rlAddOld);
                    tvVersionInfo = (TextView) view.findViewById(R.id.tvVersionInfo);
                    tvExit = (TextView) view.findViewById(R.id.tv_exit);
                    break;

            }

        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case tv_notice://打开 关闭 通知
                fragmentMy.exChangeNotice(isNotice);
                break;
            case R.id.miv_about_us://关于我们
                Intent mIntent = new Intent(context, AboutUsActivity.class);
                context.startActivity(mIntent);
                break;

            case R.id.miv_clear_cache://清楚缓存
                clearCache();
                break;

            case R.id.tv_exit://退出
                if (fragmentMy != null)
                    fragmentMy.quit();
                break;

            case R.id.sdv_head://进入个人设置页面
                Intent nIntent = new Intent(context, SettingActivity.class);
                context.startActivity(nIntent);
                break;

            case R.id.rlAddOld://添加老人
                Intent intent = new Intent(context, AddOldActivity.class);
                context.startActivity(intent);
                break;
        }

    }


    /**
     * 清除缓存
     */
    private void clearCache() {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {

                Fresco.getImagePipelineFactory().getMainFileCache().trimToMinimum();
                long cacheSize = Fresco.getImagePipelineFactory().getMainFileCache().getSize();
                Log.d(TAG, "缓存的图片大小:" + (cacheSize / 1024 / 1024) + "M");

                ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();

                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                imagePipeline.clearMemoryCaches();
                imagePipeline.clearDiskCaches();
                imagePipeline.clearCaches();
                e.onNext("");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String value) {
                        Toast.makeText(context, "清除成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }


    /**
     * 获取当前的版本信息
     *
     * @return
     */
    private String getCurrentVersion() {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
//            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }
        return versionName;
    }
}